package js.web.center.web;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.script.ScriptException;

import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

import js.web.center.core.config.JsWebConfig;
import js.web.center.script.core.JsWebScriptEngineCore;
/**
 * websocket接入口
 * @author dowell
 *
 */
@WebSocket(maxTextMessageSize=128*1024,maxBinaryMessageSize=128*1024)
public class JsWebSocketAnnotated {
	private static Logger logger=Logger.getLogger(JsWebSocketAnnotated.class);
	private static JsWebScriptEngineCore engineCore=null;
	private Session session;
	@OnWebSocketConnect
	public void connect(Session session){
		this.session=session;
	}
	@OnWebSocketClose
	public void close(int statusCode,String reason){
		try {
			engineCore.function("close",this.session);
		} catch (NoSuchMethodException e) {
			logger.error("JsWebSocketAnnotated ERROR:{}",e);
		} catch (ScriptException e) {
			logger.error("JsWebSocketAnnotated ERROR:{}",e);
		}
		this.session=null;
	}
	@OnWebSocketMessage
	public void message(String msg){
		sendMsg(msg);
	}
	/**
	 * 发送消息到客户端
	 * @param js.web.center.web.session
	 * @param msg
	 */
	public void send(Session session,Object msg){
		if(session!=null){			
			if(session.isOpen()){		
				try {
					session.getRemote().sendString(msg.toString());
				} catch (IOException e) {
					logger.error("JsWebSocketAnnotated ERROR:{}",e);
				}
			}
		}
	}
	/**
	 * 直接把消息转发到js中
	 * @param msg
	 */
	private void sendMsg(String msg){
		if(engineCore==null){
			engineCore=new JsWebScriptEngineCore();
			try {
				engineCore.init(JsWebConfig.WEB_SOCKET);
				engineCore.init(JsWebConfig.LIBS_BASE);
				engineCore.appParams(JsWebConfig.SELF, this);
				engineCore.appParams(JsWebConfig.PARENT, engineCore);
			} catch (FileNotFoundException e) {
				logger.error("JsWebSocketAnnotated ERROR:{}",e);
			} catch (ScriptException e) {
				logger.error("JsWebSocketAnnotated ERROR:{}",e);
			}
		}
		try {
			engineCore.function(JsWebConfig.HANDLER,session, msg);
		} catch (NoSuchMethodException e) {
			logger.error("JsWebSocketAnnotated ERROR:{}",e);
		} catch (ScriptException e) {
			logger.error("JsWebSocketAnnotated ERROR:{}",e);
		}
	}
	/**
	 * 日志打印
	 * @param object
	 */
	public void log(Object object){
		logger.info(object.toString());
	}
}